var _base64 = new Base64(),
  sm4 = new SM4Util(),
  LG = {
    el: '#app',
    data: function () {
      var _that = this;
      var checkSame = function (rule, value, callback) {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== _that.editPasswordData.newPassword) {
          callback(new Error('两次输入密码不一致！'));
        } else {
          callback();
        }
      };
      var checkDiffer = function (rule, value, callback) {
        //密码包含 数字,英文,字符中的两种以上，长度8-20
        var patrn = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,20}$";
        var re = new RegExp(patrn);
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (value == _that.editPasswordData.oldPassword) {
          callback(new Error('新密码和原密码不能相同！'));
        } else if (!re.test(value)) {
          callback(new Error('密码需含数字,英文,字符的两种，长度8-20'));
        } else {
          callback();
        }
      };
      // 校验旧密码是否输入正确
      var checkOldPass = function (rule, value, callback) {
        if (value === '') {
          callback(new Error('请输入原密码'));
        } else {
          var _type = _that.loginConfig.encryptType,
            params = {};
          if (_type == 0) {
            params = {
              loginName: _base64.encode(_that.lgForm.username),
              oldPassword: sm3(hex_md5(value)),
            }
          } else if (_type == 1) {
            params = {
              loginName: sm4.encryptData_ECB(_that.lgForm.username),
              oldPassword: sm3(hex_md5(value)),
              proPassword: sm3(sm4.encryptData_ECB(value))
            }
          }
          request('agx', {
            url: _that.loginConfig.ssoServerUrl + '/authentication/user/passwordCheckout',
            data: params,
            type: 'get'
          }, function (data) {
            if (data.success) {
              callback();
            } else {
              callback(new Error(data.message ? data.message : '原密码错误'));
            }
          })
        }
      };
      return {
        ctx: ctx,
        loading: false, // 
        loginConfig: {
          encryptType: '', //登录加密类型 0：MD5 1:sm4
          useTitleImage: 0,
        }, //登录方案数据
        lgForm: {
          username: '', //
          password: '', //
          proPassword: '', //密码
          imageCode: '',
          isPcGetToken: 'true'
        },
        lgRules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          imageCode: [{
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }],
        },
        lgLoading: false, //登录按钮loading
        lgMsg: null, //登录信息提示
        showLgMsg: false, //是否显示登录信息提示
        loginBtnObj: {
          tip: '登录',
          isDisabled: false
        },//登录按钮提示
        
        slObj: {
          slOrgDg: false, //是否显示选择组织dialog
          slForm: {
            orgId: '', //选择的组织id
          },
          slRules: {
            orgId: [{required:true, message: '请选择', trigger: 'blur'}]
          },
          slOrgOptions: [], //待选取组织列表
        },

        // 修改密码
        editPasswordFlag: false, // 是否展示修改密码弹窗
        dialogTitie: '修改密码',
        editPasswordData: {
          oldPassword: '',
          newPassword: '',
          newPasswordCheck: ''
        }, // 修改密码data
        newPasswordCheck: '', // 再次确认新密码
        editPasswordRule: {
          oldPassword: [{
            required: true,
            validator: checkOldPass,
            trigger: 'blur'
          }, ],
          newPassword: [{
            validator: checkDiffer,
            required: true,
            trigger: 'blur'
          }],
          newPasswordCheck: [{
            validator: checkSame,
            required: true,
            trigger: 'blur'
          }]
        }, // 修改密码校验
        verCodeObj: {
          src: '',
          GUID:''
        },
        forgetPasswordFlag: false, //是否开启忘记密码配置
      }
    },
    methods: {
       // 通用-form-校验信息清除
      _formFiledsReset: function (formName, keys) {
        var _that = this;
        setTimeout(function () {
          _that.$refs[formName].clearValidate(keys);
        }, 100)
      },
      // 通用-判断是否为ie浏览器
      isIE:function() { 
        if (!!window.ActiveXObject || "ActiveXObject" in window)
         return true;
         else
         return false;
      },
      // 获取page-url参数
      getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
        var context = "";
        if (r != null)
          context = r[2];
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
      },
      // 获取校验吗
      getCode: function () {
        var _that = this;
        // $('#verifyCodeImg').attr("src", _that.loginConfig.ssoServerUrl + 'code/image?time1=' + new Date().getTime());
        var _that = this;
        // _that.loading = true;
        request('sso', {
          url: _that.loginConfig.ssoServerUrl + '/code/guidImage',
          type: 'get',
        }, function (data) {
          // _that.loading = false;
          if (data.success) {
            _that.verCodeObj.src = data.content.image;
            _that.verCodeObj.GUID = data.content.GUID;
          } else {
            _that.$message.error(data.message ? data.message : '获取失败');
          }
        }, function (msg) {
          // _that.loading = false;
          _that.$message.error(msg.message ? msg.message : '服务器错了哦!');
        });
      },

      // 获取方案数据
      fetchLoginConfigFn: function () {
        var _that = this;
        _that.loading = true;
        request('sso', {
          url: ctx + 'loginConfig',
          type: 'get',
        }, function (data) {
          _that.loading = false;
          if (data.success) {
            _that.loginConfig = data.content || [];
            _that.handelLgConfFn();
          } else {
            _that.$message.error(data.message ? data.message : '获取失败');
          }
        }, function (msg) {
          _that.loading = false;
          _that.$message.error(msg.message ? msg.message : '服务器错了哦!');
        });
      },
      // 处理登录方案接口数据
      handelLgConfFn: function () {
        var _that = this,
          _conf = _that.loginConfig;
        // 是否使用背景图
        if (_conf.useBgImage == 1) {
          if(_that.isIE()){
            document.body.style.background = 'url(' + _that.loginConfig.bgImage + ')';
            return;
          }
          document.documentElement.style.setProperty('--bgImg', 'url(' + _that.loginConfig.bgImage + ')');
        }
      },
      // 登录
      loginFn: function () {
        var _that = this;
        _that.$refs['lgForm'].validate(function (valid) {
          if (valid) {
            login();
          } else {
            // _that.$message.warning('请完善登录信息');
            _that.showLgMsg = true; //显示提示
            _that.lgMsg = '请完善登录信息';
            return false;
          }
        })

        function login() {
          _that.lgLoading = true;
          var param = JSON.parse(JSON.stringify(_that.lgForm)),
            _type = _that.loginConfig.encryptType;
          if (_type == 0) {
            param.username = _base64.encode(param.username);
            param.password = sm3(hex_md5(param.password));
            param.deviceType = _base64.encode(_that.loginConfig.deviceType);
          } else if (_type == 1) {
            param.username = sm4.encryptData_ECB(param.username);
            param.password = sm3(hex_md5(param.password));
            param.proPassword = sm3(sm4.encryptData_ECB(_that.lgForm.password));
            param.deviceType = sm4.encryptData_ECB(_that.loginConfig.deviceType);
          }
          param.enableErrorRule = _that.loginConfig.enableErrorRule;
          if(_that.loginConfig.needCaptcha == 1)param.GUID = _that.verCodeObj.GUID;
          if(_that.loginConfig.needCaptcha != 1) delete param.imageCode;
          $.ajax({
            url:  _that.loginConfig.ssoServerUrl + '/authentication/form',
            data: param,
            type:'post',
            headers:{
              "Authorization": 'Basic '+ _that.loginConfig.clientAuth,
              "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
              "isAgAjax":true
            },
            //加上这句话
            xhrFields: {
              withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
              _that.lgLoading = false;
              _that.loginAfterFn(data.content);
            },
            error:function (error) {
              _that.lgLoading = false;
              _that.$message({
                message: error.message || '登录失败，请重新登录',
                type: 'error'
              });
            }
          });
        }
      },
      // 登录成功后逻辑
      loginAfterFn: function (content) {
        var _that = this,
          code = content.msgCode; //类型
        _that.showLgMsg = true; //显示提示
        // 账密错误 accountPwdErrFn
        // 账号锁定 accountLockedFn
        // 强制修改密码 forceChangePwd
        // 提示修改密码 remindChangePwd
        // 登录成功 loginSuccess
        // 提示
        // code='ACCOUNT_LOCKED';
        function showTip() {
          _that.lgForm.password = '';
          _that.lgForm.imageCode = '';
          return _that.lgMsg = content.message;
          // return alertMsg('', content.message, '关闭', 'error', true);
        }
        var codeAction = {
          'ACCOUNT_PASSWORD_ERROR': function accountPwdErrFn() {
            // _that.$message.error('账号或密码错误，请重新输入！');
            _that.lgMsg = content.message || '账号或密码错误，请重新输入！';
            _that.lgForm.password = '';
            _that.lgForm.imageCode = '';
            _that.getCode();
            // return alertMsg('', '账号或密码错误，请重新登录！', '关闭', 'error', true);
          },
          'ACCOUNT_LOCKED': function accountLockedFn() {
            // _that.$message.error('您的账号已被锁定，请稍后登录！');
            _that.lgMsg = '您的账号已被锁定，请稍后登录！';
            _that.lgForm.imageCode = '';
            // return alertMsg('', '您的账号已被锁定，请稍后登录！', '关闭', 'error', true);
            // 跑计时逻辑
            _that.showCutDownFn(_that.loginConfig.loginWaitDuration,_that.loginBtnObj,function(){
              _that.lgMsg = '';
              _that.showLgMsg = false; 
              _that.getCode();
            });
          },
          'FORCE_CHANGE_PASSWORD': function forceChangePwd() {
            _that.lgMsg = content.message || '请修改密码！';
            _that.dialogTitie = _that.lgMsg || '修改密码';//弹框title修改
            _that.lgForm.password = '';
            _that.lgForm.imageCode = '';
            _that.editPasswordFlag = true;
            _that.editPasswordData= {
              oldPassword: '',
              newPassword: '',
              newPasswordCheck: ''
            };   
            _that.$nextTick(function(){
              _that.pwStrength('');
              _that._formFiledsReset('editPasswordData', ['oldPassword','newPassword','newPasswordCheck']);
            })
          },
          'REMIND_CHANGE_PASSWORD': function remindChangePwd() {
            _that.showLgMsg = false;
            _that.$alert('您的密码安全性较低，请及时修改密码！', '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: function (action) {
                codeAction['LOGIN_SUCCESS']();
              }
            });
          },
          'LOGIN_SUCCESS': function loginSuccess() {
            // _that.$message.success('登录成功！');
            _that.showLgMsg = false;
            // 添加重定向逻辑，从登录页的reBackurl来判断目标地址，不存在即默认跳转首页
            var reBackurl = '';
            reBackurl = _base64.decode(_that.getQueryString('reBackurl'))  || _that.loginConfig.redirectUrl;
            setTimeout(function () {
              // window.location.href = content.redirectUrl;
              localStorage.setItem("access_token",content.access_token);
                //window.location.href = "http://localhost:7010/opus-admin-ui/admin";
              if(_that.loginConfig.redirectUrl.indexOf('opus-portal-ui') > -1){
                document.cookie = "lName=" + _that.lgForm.username + "; path=/opus-portal-ui";
              }
              window.location.href = reBackurl;
            }, 80)
          },
          'VALIDATE_CODE': function validateCodeFn() {
            _that.lgForm.imageCode = '';
            _that.getCode();
            return _that.lgMsg = content.message;
            // return _that.$message.error(content.message);
          },
          'MORE_ROOT_ORG':function selectOrgFn(){
            _that.lgMsg = content.message;
            // setTimeout(function(){
              _that.slObj.slOrgDg = true;
              _that.slObj.slOrgOptions = content.rootOrgList || [];
              _that.slObj.slForm.orgId = _that.slObj.slOrgOptions[0].orgId || '';
              _that.$nextTick(function(){
                _that.$refs.slForm.clearValidate(['orgId']);
              })
            // },500)
          },
        };
        return codeAction[code] ? codeAction[code]() : showTip();
      },
      // 选择组织后的登录逻辑
      slLoginFn: function(){
        var _that = this;
        _that.$refs['slForm'].validate(function (valid) {
          if (valid) {
            login();
          } else {
            _that.$message.warning('请选择组织');
            return false;
          }
        })

        function login() {
          _that.loging = true;
          var param = JSON.parse(JSON.stringify(_that.lgForm)),
            _type = _that.loginConfig.encryptType;
          delete param.imageCode;
        
          if (_type == 0) {
            param.username = _base64.encode(param.username);
            param.password = sm3(hex_md5(param.password));
            param.deviceType = _base64.encode(_that.loginConfig.deviceType);
            param.orgId = _base64.encode(_that.slObj.slForm.orgId);
          } else if (_type == 1) {
            param.username = sm4.encryptData_ECB(param.username);
            param.password = sm3(hex_md5(param.password));
            param.proPassword = sm3(sm4.encryptData_ECB(_that.lgForm.password));
            param.deviceType = sm4.encryptData_ECB(_that.loginConfig.deviceType);
            param.orgId = sm4.encryptData_ECB(_that.slObj.slForm.orgId);
          }
          param.enableErrorRule = _that.loginConfig.enableErrorRule;
          request('sso', {
            url: _that.loginConfig.ssoServerUrl + '/authentication/form',
            type: 'post',
            data: param
          }, function (data) {
            _that.loging = false;
            _that.loginAfterFn(data.content); //登录成功后逻辑处理
          }, function (msg) {
            _that.loging = false;
            _that.$message.error('服务器错了哦!');
          });
        }

      },
      // 展示倒计时
      showCutDownFn: function (time, _obj, cb) {
        var _that = this,
          _timer = null;
        _obj.isDisabled = true;
        _obj.tip = '（' + time + '秒）后重新登录';
        if (time < 0) {
          _obj.tip = "登录";
          _obj.isDisabled = false;
          window.clearTimeout(_timer);
          return cb && cb();
        }
        _timer = setTimeout(function () {
          --time;
          _that.showCutDownFn(time, _obj, cb);
        }, 1000)
      },

      editPasswordSubmit: function () {
        var _that = this;
        _that.$refs['editPasswordData'].validate(function (valid) {
          if (valid) {

            var props = {},
              _type = _that.loginConfig.encryptType;
            if (_type == 0) {
              props = {
                loginName: _base64.encode(_that.lgForm.username),
                oldPassword: sm3(hex_md5(_that.editPasswordData.oldPassword)),
                newPassword: hex_md5(_that.editPasswordData.newPassword)
              }
            } else if (_type == 1) {
              props = {
                loginName: sm4.encryptData_ECB(_that.lgForm.username),
                oldPassword: sm3(hex_md5(_that.editPasswordData.oldPassword)),
                proPassword: sm3(sm4.encryptData_ECB(_that.editPasswordData.oldPassword)),
                newPassword: sm3(sm4.encryptData_ECB(_that.editPasswordData.newPassword)),
              }
            }
            request('sso', {
              url: _that.loginConfig.ssoServerUrl + '/authentication/user/password',
              data: props,
              type: 'post'
            }, function (data) {
              if (data.success) {
                _that.$message.success('密码修改成功');
                _that.editPasswordFlag = false;
              } else {
                _that.$message.error(data.message ? data.message : '密码修改失败');
              }
            }, function (msg) {
              _that.$message.error(msg.message ? msg.message : '密码修改失败');
            })
          } else {
            _that.$message.warning('请完善需要修改的信息');
            return false;
          }
        });
      },

      /**********新密码等级校验-start***********/
      //测试某个字符是属于哪一类.
      CharMode: function (iN) {
        if (iN >= 48 && iN <= 57) //数字
          return 1;
        if (iN >= 65 && iN <= 90) //大写字母
          return 2;
        if (iN >= 97 && iN <= 122) //小写
          return 4;
        else
          return 8; //特殊字符
      },
      //计算出当前密码当中一共有多少种模式
      bitTotal: function (num) {
        var modes = 0;
        for (i = 0; i < 4; i++) {
          if (num & 1) modes++;
          num /= 2;
        }
        return modes;
      },
      //返回密码的强度级别
      checkStrong: function (sPW) {
        if (sPW.length <= 4)
          return 0; //密码太短
        var Modes = 0;
        for (i = 0; i < sPW.length; i++) {
          //测试每一个字符的类别并统计一共有多少种模式.
          Modes |= this.CharMode(sPW.charCodeAt(i));
        }
        return this.bitTotal(Modes);
      },
      //当用户放开键盘或密码输入框失去焦点时，根据不同的级别显示不同的颜色 
      pwStrength: function (pwd) {
        var O_color = "#eeeeee";
        var L_color = "#FF0000";
        var M_color = "#FF9900";
        var H_color = "#33CC00";
        var Lcolor = '',
          Mcolor = '',
          Hcolor = '';
        if (pwd == null || pwd == '') {
          Lcolor = Mcolor = Hcolor = O_color;
        } else {
          S_level = this.checkStrong(pwd);
          switch (S_level) {
            case 0:
              Lcolor = Mcolor = Hcolor = O_color;
            case 1:
              Lcolor = L_color;
              Mcolor = Hcolor = O_color;
              break;
            case 2:
              Lcolor = Mcolor = M_color;
              Hcolor = O_color;
              break;
            default:
              Lcolor = Mcolor = Hcolor = H_color;
          }
        }
        // console.log(Lcolor,Mcolor,Hcolor)
        // return
        var doc = document;
        doc.getElementById("strength_L").style.background = Lcolor;
        doc.getElementById("strength_M").style.background = Mcolor;
        doc.getElementById("strength_H").style.background = Hcolor;
      },
      /**********新密码等级校验-end***********/

      // 判断是否本地测试环境
      isLocalFn: function () {
        var _that = this,
          IS_LOCAL = window.location.protocol === 'file:' ? true : false;
        // 如果是本地测试环境
        if (IS_LOCAL) {
          ctx = 'http://192.168.3.45:7010/opus-admin-ui/'; //zhaoxiong  
          _that.fetchLoginConfigFn();
        } else {
          _that.loginConfig = LOGIN_CONFIG ? JSON.parse(LOGIN_CONFIG) : _that.fetchLoginConfigFn();
          _that.handelLgConfFn();
        }
        return IS_LOCAL;
      },
    },

    created: function () {
      var _that = this;
      _that.isLocalFn();
      if(_that.loginConfig.needCaptcha == 1)_that.getCode();
      _that.forgetPasswordFlag = FORGETPASSWORDFLAG;
    },
    mounted: function () {
      var _that = this;
      document.addEventListener('keydown', function (event) {
        if (event.keyCode == 13) {
          _that.loginFn();
        }
      });
    },
  }
var app = new Vue(LG);